package com.lijinjiang.view;

import com.lijinjiang.exception.QueryException;
import com.lijinjiang.model.GlobalContext;
import com.lijinjiang.model.ViewObject;
import com.lijinjiang.model.tree.Database;
import com.lijinjiang.model.tree.Table;
import com.lijinjiang.util.ImageUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/**
 * @ClassName RightPane
 * @Description 主界面的右边面板
 * @Author Li
 * @Date 2022/8/19 23:05
 * @ModifyDate 2022/8/19 23:05
 * @Version 1.0
 */
public class RightPane extends JTabbedPane {
    // 全局上下文环境
    private GlobalContext ctx;
    // 主界面
    private MainFrame mainFrame;
    // 对象页
    private JScrollPane objectPane;
    // 对象列表
    private JList objectList;
    // 右键菜单
    private TabbedMenu tabbedMenu;

    public JList getObjectList() {
        return objectList;
    }

    public void setObjectList(JList objectList) {
        this.objectList = objectList;
    }

    // 构造方法
    public RightPane(GlobalContext ctx, MainFrame mainFrame) {
        this.ctx = ctx;
        this.mainFrame = mainFrame;
        this.setFocusable(false); // 不显示按钮的虚框
        // 移除所有鼠标监听
        MouseListener[] listeners = this.getMouseListeners();
        for (MouseListener listener : listeners) {
            this.removeMouseListener(listener);
        }
        createObjectList();
        objectPane = new JScrollPane(objectList);
        // 添加对象选项卡
        this.addTab("对象", objectPane);
        JPanel tabComponent = new JPanel();
        tabComponent.setOpaque(false); // 设置背景透明
        JLabel titleLabel = new JLabel("  对象  ");
        tabComponent.add(titleLabel);
        this.setTabComponentAt(0, tabComponent);

        tabbedMenu = new TabbedMenu(this);
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                int index = RightPane.this.indexAtLocation(e.getX(), e.getY()); // 鼠标点击位置的选项卡索引
                // 实现左键切换选项卡
                if (e.getModifiers() == MouseEvent.BUTTON1_MASK) {
                    if (index > -1) {
                        RightPane.this.setSelectedIndex(index);
                    }
                } else if (e.getModifiers() == MouseEvent.BUTTON3_MASK) {
                    // 右键点击，弹出菜单
                    if (index > -1) {
                        RightPane.this.tabbedMenu.showTabbedMenu(e);
                    }
                }
            }
        });
        objectPane.setBorder(null);
        this.setBorder(null);
    }

    private JList createObjectList() {
        objectList = new JList();
        // 设置先纵向后横向滚动
        objectList.setLayoutOrientation(JList.VERTICAL_WRAP);
        objectList.setFixedCellHeight(30); // 设置要用于列表中每个单元格的固定高度
        objectList.setVisibleRowCount(this.HEIGHT / 30);
        objectList.setCellRenderer(new DefaultListCellRenderer() {
            public Component getListCellRendererComponent(JList list, Object value,
                                                          int index, boolean isSelected, boolean cellHasFocus) {
                JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                ViewObject object = (ViewObject) value;
                label.setIcon(object.getIcon());
                return this;
            }
        }); // 设置列表渲染类
        objectList.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                // 左键双击
                if (e.getClickCount() == 2 && e.getModifiers() == MouseEvent.BUTTON1_MASK) {
                    Object value = objectList.getSelectedValue();
                    if (value instanceof Table) {
                        showTableData((Table) value);
                    }
                }
            }
        });
        objectList.setBorder(null);
        return objectList;
    }

    // 设置对象页的数据
    protected void setObjectPaneData(Object[] data) {
        this.objectList.setListData(data);
    }

    // 插入一页
    public void addTabPage(Icon icon, String title, Component component) {
        JPanel tabComponent = new JPanel();
        tabComponent.setOpaque(false); // 设置背景透明
        tabComponent.setLayout(new BorderLayout());
        JLabel iconLabel = new JLabel(); // 选项卡图标
        iconLabel.setIcon(icon);
        tabComponent.add(iconLabel, BorderLayout.WEST);
        JLabel titleLabel = new JLabel(title); // 选项卡标题
        tabComponent.add(titleLabel, BorderLayout.CENTER);
        JLabel closeLabel = new JLabel();
        closeLabel.setIcon(ImageUtil.CLOSE_ICON); // 选项卡关闭图标
        tabComponent.add(closeLabel, BorderLayout.EAST);

        int count = this.getTabCount();
        this.insertTab(title, icon, component, null, count); // 添加组件
        this.setTabComponentAt(count, tabComponent);

        // 关闭的图片添加监听，点击关闭
        closeLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (e.getModifiers() == MouseEvent.BUTTON1_MASK) {
                    JLabel source = (JLabel) e.getSource();
                    Component parent = source.getParent();
                    RightPane.this.removeTabAt(RightPane.this.indexOfTabComponent(parent));
                }
            }

            // 鼠标移上去切换关闭图标
            @Override
            public void mouseEntered(MouseEvent e) {
                closeLabel.setIcon(ImageUtil.CLOSE_ENTERED_ICON);
            }

            // 鼠标移走，图标恢复
            @Override
            public void mouseExited(MouseEvent e) {
                closeLabel.setIcon(ImageUtil.CLOSE_ICON);
            }
        });

        this.setSelectedIndex(count); // 切换到数据显示页
    }

    // 显示表单数据
    public void showTableData(Table table) {
        if (table != null) {
            Database db = table.getDatabase();
            String title = "  " + table.getTableName() + "@" + db.getDbName() + "  ";
            int count = this.getTabCount();
            for (int i = 0; i < count; i++) {
                String s = this.getTitleAt(i);
                if (s.equalsIgnoreCase(title)) {
                    this.setSelectedIndex(i);
                    return;
                }
            }
            try {
                String sql = "select * from " + table.getTableName();
                DataTable dataPanel = new DataTable(db, sql);
                addTabPage(ImageUtil.TABLE_ICON, title, dataPanel);
                dataPanel.setBorder(null);
            } catch (QueryException se) {
                JOptionPane.showMessageDialog(this.mainFrame, se.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
        } else {
            System.out.println("表单为空！");
        }
    }

    // 创建查询面板
    public void createQueryPanel(Database db) {
        QueryPanel queryPanel = new QueryPanel(mainFrame, db);
        String title = "  " + "无标题 - 查询" + "  ";
        addTabPage(ImageUtil.QUERY_ICON, title, queryPanel);
    }
}
